package compendiumAid.presentation.sortMethods
{
	import compendiumAid.domain.model.ApplicationModel;
	import compendiumAid.presentation.PresentationModel;
	
	import mx.collections.ArrayCollection;
	import mx.collections.Sort;
	import mx.core.FlexGlobals;
	import mx.core.UIComponent;
	import mx.managers.PopUpManager;
	
	public class SortMethodsPM extends PresentationModel
	{
		[Inject]
		[Bindable]
		public var model:ApplicationModel;
		
		[Bindable]
		public var available:ArrayCollection = new ArrayCollection(['Level', 'Classification']);
		
		[Bindable]
		public var selected:ArrayCollection = new ArrayCollection(['Name']);
		
		private var currentPopUp:UIComponent;
		
		public function showPopUp():void
		{
			if (currentPopUp == null)
			{
				currentPopUp = new SortMethodsPopUp;
				(currentPopUp as SortMethodsPopUp).pm = this;
				
				PopUpManager.addPopUp( currentPopUp, FlexGlobals.topLevelApplication.root, true );
				PopUpManager.centerPopUp( currentPopUp );
			}
		}
		
		public function removeMethod(method:String):void
		{
			if (method != null)
			{
				transfer(method, selected, available);
			}
		}
		
		public function addMethod(method:String):void
		{
			if (method != null)
			{
				transfer(method, available, selected);
			}
		}
		
		public function addAllMethods():void
		{
			for (var i:int = available.length - 1; i >= 0; i--)
			{
				var method:String = available[i];
				addMethod(method);
			}
		}
		
		public function removeAllMethods():void
		{
			for (var i:int = selected.length - 1; i >= 0; i--)
			{
				var method:String = selected[i];
				removeMethod(method);
			}
		}
		
		public function save():void
		{
			close();
		}
		
		public function close():void
		{
			if (currentPopUp != null)
			{
				PopUpManager.removePopUp(currentPopUp);
				currentPopUp = null;
				selected.refresh();
			}
		}
		
		private function transfer(method:String, from:ArrayCollection, to:ArrayCollection):void
		{
			var index:int = from.getItemIndex(method);
			
			if ((index >= 0) && (index < from.length))
			{
				from.removeItemAt(index);
			}
			
			to.addItem(method);
		}
	}
}